#include <deque>
#include <vector>
#include "snake.h"
#include "map.h"
#include <iostream>
#include "share.h"
#include <algorithm>
#include <windows.h> 
#include "get_peak_score.h"

std::deque<SnakeSegment> snake;




enum Direction { UP, DOWN, LEFT, RIGHT };
Direction currentDir = RIGHT;  
int moveInterval = 350;        
const int STEP_SIZE = 2;       
int score_unit = 1;


void initSnake() {
    snake.clear();
    currentDir = RIGHT;
    int tailX = 24, tailY = 5;  
    for (int i = 0; i < 5; ++i) {
        int x = tailX + 2 * i;
        int y = tailY;
        snake.push_back({x, y});

        if (x <= MAP_WIDTH && y <= MAP_HEIGHT) {
            gameMap[y][x] = 's';  
        }
    }
}


void speedup() {
    moveInterval = 10;
    moveInterval = max(moveInterval, 10);
    score_unit = score_unit + 2;
}
void speeddown() {
        moveInterval = moveInterval + 30;
        moveInterval = min(moveInterval, 350);
    if(moveInterval <= 320) {
        score_unit = max(score_unit - 2, 2);
    }
    else{
        score_unit = 1;
    }
}


void snakeMove() {
    if (snake.empty()) return;
    SnakeSegment newHead = snake.back(); 
    switch (currentDir) {
        case UP:    newHead.y--; break;
        case DOWN:  newHead.y++; break;
        case LEFT:  newHead.x -= STEP_SIZE; break;
        case RIGHT: newHead.x += STEP_SIZE; break;
    }
    //鉴是否碰墙
    if (newHead.x <= 0 || newHead.x >= MAP_WIDTH || 
        newHead.y <= 0 || newHead.y >= MAP_HEIGHT) {
        gameOver = true;
        mode_now = 4;
    }
    //鉴是否自撞
    for (const auto& seg : snake) {
        if (newHead.x == seg.x && newHead.y == seg.y) {
            gameOver = true;
            mode_now = 4;
        }
    }

    //插入新头部
    snake.push_back(newHead);
    
    // 食物检测与处理
    if (newHead.x == food.x && newHead.y == food.y) {
        createFood();
        score += score_unit;
        speedup();
    } else {
        //移除尾部并更新地图
        SnakeSegment tail = snake.front();
        gameMap[tail.y][tail.x] = ' ';  // 清除旧尾部
        snake.pop_front();
    }

    // 更新蛇身地图标记
    for (const auto& seg : snake) {
        if (seg.x <= MAP_WIDTH && seg.y <= MAP_HEIGHT) {
            gameMap[seg.y][seg.x] = 's';
        }
    }
    peak_score = max(peak_score, score);
    overwriteFile(peak_score);
}

// 方向控制函数
void handleInput() {
    // 方向键检测
    if (GetAsyncKeyState(VK_UP) & 0x8000) {     
        if (currentDir != DOWN) currentDir = UP; 
    } 
    else if (GetAsyncKeyState(VK_DOWN) & 0x8000) { 
        if (currentDir != UP) currentDir = DOWN;
    }
    else if (GetAsyncKeyState(VK_LEFT) & 0x8000) { 
        if (currentDir != RIGHT) currentDir = LEFT;
    }
    else if (GetAsyncKeyState(VK_RIGHT) & 0x8000) { 
        if (currentDir != LEFT) currentDir = RIGHT;
    }

    // 功能键检测
    if (GetAsyncKeyState(VK_F1) & 0x8000) {
        if(moveInterval == 10);
        else{
            speedup();
        }    
    }
    if (GetAsyncKeyState(VK_F2) & 0x8000) { 
        speeddown();
    }
}





